<template>
	<view class="container">
		<!--显示当前的位置信息-->
		<view class="status_bar"></view>
		<view style="height: 90rpx; line-height: 110rpx;text-align: center;">
			<text style="margin-left: 120rpx;" @tap="chooseCity">{{i18n.recommend}}.{{current_city}}</text>
			<text style="float: right; margin-right: 30rpx;" @click="goSearch">
				<uni-icons type="search"></uni-icons>搜索
			</text>
		</view>
		<!-- 头部轮播 -->
		<view class="carousel-section">
			<swiper class="carousel" autoplay :indicator-dots='true' circular @change="swiperChange">
				<swiper-item v-for="(item, index) in carouselList" :key="index" class="carousel-item" @tap="navToDetailPage(item.detail_id)">
					<image :src="item.pic_url" />
				</swiper-item>
			</swiper>
		</view>
		<view class="news-section" v-if="recommend.news.id != undefined">
			<view class="intr-box">
				<text class="title">{{i18n.recommend_news}}</text>
				<view class="goto-btn" @click="goNews(recommend.news.id)">
					<text class="yticon icon-you"></text>
				</view>
			</view>
			<text class="intro">{{recommend.news.introduce}}</text>
		</view>
		<view class="news-section" v-if="recommend.shop.length > 0">
			<view class="intr-box">
				<text class="title">{{i18n.recommend_shop}}</text>
				<view class="goto-btn">
					<!-- <text class="yticon icon-you"></text> -->
				</view>
			</view>
			<view class="uni-flex uni-row">
				<view v-for="(item,index) in recommend.shop" class="text" style="-webkit-flex: 1;flex: 1;" @click="goShop(item.id)">
					<image class="image intr-img" mode="widthFix" :src="item.logo" />
				</view>
			</view>
		</view>
		<view id="products" style="margin-bottom: 100rpx;" >
			<view v-for="(item,index) in productList" id="products_view">
				<view v-if="index % 2 == 0" class="uni-flex uni-row" style="-webkit-justify-content: space-between;justify-content: space-between;">
					<ProductItem :item="productList[index]" style="width: 50%;background-color: rgb(251, 240, 240);"></ProductItem>
					<ProductItem v-if="index+1 < productList.length" :item="productList[index+1]" style="width: 50%;background-color: rgb(251, 240, 240);"></ProductItem>
				</view>
			</view>
		</view>
		
		<uni-load-more style="margin-top: -30px;" :status="more"></uni-load-more>
		<luna-upgrade ref="showtip" :nowversion="nowversion" :newversion="newversion" :url="upgrade.url" :notes="upgrade.notes" :lang="lang"></luna-upgrade>
	</view>
</template>

<script>
	import {
		mapState,
	    mapMutations  
	} from 'vuex';
	import Config from '../../common/config.js'
	import request from '../../common/request.js';
	import LunaUpgrade from '@/components/luna-upgrade/luna-upgrade.vue';
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import ProductItem from '../common/product_item_z.vue'
	export default {
		components: { LunaUpgrade, uniIcons, ProductItem},
		data() {
			return {
				swiperCurrent: 0,
				swiperLength: 0,
				carouselList: [],
				productList: [],
				current_city: uni.getStorageSync('current_city') ? uni.getStorageSync('current_city') : '全国',
				location: null,
				page: 1,
				size: 6,
				hasMore: true,
				nowversion: '',
				newversion: '',
				lang: {},
				more: 'contentrefresh',
				isLoading: false,
				recommend : {
					news: {},
					shop: []
				}
			};
		},
		computed: {
			...mapState(['upgrade']),
			i18n() {
				return this.$lang.index_index
			}
		},
		methods: {
			goNews(id){
				uni.navigateTo({
					url: '/pages/news/detail?id='+id
				})
			},
			goShop(id){
				uni.navigateTo({
					url: '/pages/shop/shop?id='+id
				})
			},
			goSearch() {
				uni.navigateTo({
					url:'../search/search'
				})
			},
			getCarouselList() {
				var that = this
				request({
					name: 'product.carousels',
					success(res) {
						console.log(res)
						that.carouselList = res.data.data
						console.log(that.carouselList)
					}
				})
			},
			getProduct(append = false) {
				if (this.isLoading) return false;
				this.isLoading = true
				var that = this
				request({
					name: 'product.index',
					data: {
						page: this.page,
						size: this.size
					},
					success(res) {
						console.log(res)
						that.isLoading = false
						if (append) {
							//that.productList = that.productList.concat(res.data.data)
							console.log(res.data.data);
							for (let i in res.data.data) {
								console.log('push');
								that.productList.push(res.data.data[i])
								that.hasMore = true;
								that.more = 'more'
							}
						} else if(res.data.data && res.data.data.length){
							that.productList = res.data.data
						}
						if (that.hasMore == false) {
							that.more = 'noMore'
						}
						if (that.beginRefresh) {
							uni.stopPullDownRefresh();
							that.beginRefresh = false
						}
					}
				})
			},
			getCommend : function(){
				var that = this
				request({
					name: 'index.recommend',
					data: {
					},
					success(res) {
						res = res.data;
						console.log('recommend: ', res)
						if(res.code != undefined && res.code == 0){
							if(res.data.news){
								that.recommend.news = res.data.news;
							}
							if(res.data.shop){
								that.recommend.shop = res.data.shop;
							}
						}
					}
				})
			},
			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e.detail.current;
				this.swiperCurrent = index;
			},
			//详情页
			navToDetailPage(id) {
				uni.navigateTo({
					url: `/pages/product/product?id=${id}`
				})
			},
			chooseCity() {
				console.log('location...')
				uni.navigateTo({
					url: '/pages/choose_city/choose_city',
					fail(err) {
						console.log(err)
					}
				})
			},
			getCurrentLocation() {
				var that = this
				that.getProduct()
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					fail(error) {
						
						console.log('error is:', error);
					},
					success(res) {
						console.log('success');
						uni.setStorageSync('location', res)
						if (!uni.getStorageSync('current_city') && res.address) {
							that.current_city = res.address.city == undefined ? '' : res.address.city;
							uni.setStorageSync('current_city', that.current_city);
						}
						console.log('res', res)
						that.getProduct()
					},
					complete(res) {
						console.log('complete')
					}
				})
			}
		},
		onLoad() {
			if(Config.isCourse){
				uni.navigateTo({
					url: `/pages/course/index`
				})
				return false;
			}
			this.getCarouselList()
			this.getProduct()
			this.getCommend();
			this.getCurrentLocation();
			
			this.page = 1
			this.hasMore = true
			this.current_city = uni.getStorageSync('current_city')
			console.log('get current location');
			this.getProduct();
			this.lang = this.$lang.upgrade;
			//#ifdef APP-PLUS
			console.log('upgrade', this.upgrade);
			var _that = this;
			plus.runtime.getProperty(plus.runtime.appid,function(inf){
				console.log('upgrade 2', _that.upgrade);
				if(_that.upgrade.status == 1){
					let upshowKey = 'upgrade_show_'+inf.version+'_'+inf.versionCode;
					let upshow = uni.getStorageSync(upshowKey) === false ? false : true;
					console.log('upshow', upshow);
					if(_that.upgrade.version != inf.version || _that.upgrade.versionCode != inf.versionCode){
						if(_that.upgrade.wgtUrl){
							//version版本号一定要不一样才可以wgt更新成功
							// plus.nativeUI.showWaiting("下载wgt文件...");
							plus.downloader.createDownload(_that.upgrade.wgtUrl, {filename:"_doc/update/"}, function(d,status){
								if ( status == 200 ) {
									console.log("下载wgt成功："+d.filename);  
									// 安装wgt包  
									plus.nativeUI.showWaiting("发现有更新, 安装wgt文件...");  
									plus.runtime.install(d.filename,{},function(){
										plus.nativeUI.closeWaiting();  
										console.log("安装wgt文件成功！");  
										plus.nativeUI.alert("资源更新完成, 马上重启！",function(){
											plus.runtime.restart();
										});
									},function(e){  
										plus.nativeUI.closeWaiting();  
										console.log("安装wgt文件失败["+e.code+"]："+e.message);  
										// plus.nativeUI.alert("安装wgt文件失败["+e.code+"]："+e.message);  
									});  
								} else {  
									console.log("下载wgt失败！");  
									// plus.nativeUI.alert("下载wgt失败！");  
								}  
								plus.nativeUI.closeWaiting();  
							}).start();
						}else if(upshow){
							_that.$nextTick(() => {
								_that.$refs['showtip'].open();
								_that.notes = _that.upgrade.notes;
								_that.url = _that.upgrade.url;
								_that.nowversion = inf.version + '.' + inf.versionCode;
								_that.newversion = _that.upgrade.version + '.' + _that.upgrade.versionCode;
							});
						}
						
					}else{
						//检查是否存在App资源升级包，有即静默更新
						  
					}
				}
			});
			//#endif 
		},
		onPullDownRefresh() {
			this.beginRefresh = true
			this.getCarouselList()
			this.getProduct()
		},
		onReachBottom() {
			console.log('buttom');
			if (this.hasMore) {
				this.page++;
				this.getProduct(true);
				this.hasMore = false
				this.more = 'loading';
			} else {
				this.more = 'noMore'
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f5f5f5;
	}

/* 标题简介 */
	.news-section {
		background: #fff;
		padding: 20upx 30upx;

		.title {
			font-size: 32upx;
			color: $font-color-dark;
			height: 50upx;
			line-height: 50upx;
		}
		
		.intro {
			font-size: $font-sm;
			color: $font-color-dark;
			height: 50upx;
			line-height: 50upx;
		}

		.intr-box {
			display: flex;
			align-items: baseline;
			height: 64upx;
			padding: 10upx 0;
			font-size: 26upx;
		}

		.intr-row {
			display: flex;
			align-items: center;
			height: 50upx;
			font-size: $font-sm;
			color: $font-color-light;

			text {
				margin: 10upx;
			}
		}
		.goto-btn {
			flex: 1;
			text-align: right;                                                                                          
			font-size: $font-sm;
			color: $uni-color-primary;
		}
		.intr-img{
			height: 128upx;
			width: 128upx;
			text-align: center;
		}
	}


	/* 头部 轮播图 */
	.carousel-section {
		position: relative;
		padding-top: 5px;
	}

	.carousel {
		width: 100%;
		height: 300rpx;

		.carousel-item {
			width: 100%;
			height: 100%;
			padding: 0 0upx;
			overflow: hidden;
		}

		image {
			width: 100%;
			height: 100%;
		}
	}

	#products_view {
		background-color: #FFF;
		margin-top: 10rpx;
		padding: 10rpx;
		margin: 5rpx;
	}

	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
	}
</style>
